﻿using Future.Common.Const;
using Future.Common.Exception;
using Future.IService;
using Future.Model.CacheModel;
using Future.Web.Utility;

namespace Future.Web.Extensions
{
    /// <summary>
    /// HttpContext扩展方法
    /// </summary>
    public static class HttpContextExtension
    {
        /// <summary>
        /// 从令牌提取key 从缓存获取用户信息
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public static UserCacheModel GetUserIdInfo(this HttpContext httpContext)
        {
            UserCacheModel userCacheModel;
            string userName = GetUserName(httpContext);
            ICacheService? cacheService = GlobalContext.ServiceProvider.GetService<ICacheService>();
            if (cacheService == null)
            {
                throw new ExpireException("获取缓存服务实例失败");
            }
            userCacheModel = cacheService.GetObject<UserCacheModel>(userName) ?? new UserCacheModel();
            if (userCacheModel.User == null)
            {
                throw new ExpireException("获取用户信息失败");
            }
            return userCacheModel;
        }

        /// <summary>
        /// 获取用户登录名
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public static string GetUserName(this HttpContext httpContext)
        {
            string? userName = httpContext.User.Claims.FirstOrDefault(u => u.Type == SystemConst.USERNAMECLAIM)?.Value;
            return userName ?? string.Empty;
        }
    }
}
